package org.example.core.Service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.example.Util.JWTUtil;
import org.example.core.Dto.UserLoginRequestDto;
import org.example.core.Dto.UserLoginResponseDto;
import org.example.core.Dto.common.Result;


import org.example.core.Mapper.UserMapper;
import org.example.core.Service.UserService;
import org.example.core.pojo.User;
import org.springframework.stereotype.Service;

@Service
@Slf4j

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Override
    public Result<UserLoginResponseDto> LoginByPassword(UserLoginRequestDto userLoginDto) {
        if(StrUtil.isBlank(userLoginDto.getUsername())||StrUtil.isBlank(userLoginDto.getPassword())){
            throw new RuntimeException("用户名或密码为空");
        }
        String username=userLoginDto.getUsername();
        String password=userLoginDto.getPassword();
        LambdaQueryWrapper<User> queryWrapper = Wrappers.<User>lambdaQuery().eq(User::getUsername, username)
                .or()
                .eq(User::getMobile, username);
        User user = baseMapper.selectOne(queryWrapper);
        if(user==null){
            throw new RuntimeException("用户名或密码不正确1");
        }
        //密码校验（通过md5加密）
        if(!BCrypt.checkpw(password,user.getPassword())){
            log.info("用户名："+username+"密码："+password);
            throw new RuntimeException("用户名或密码不正确2");
        }

       //生成jwt令牌
        String s = JWTUtil.GetJwt(user.getId(), user.getUsername());

        UserLoginResponseDto userLoginResponseDto = new UserLoginResponseDto();
        userLoginResponseDto.setName(user.getUsername());
        userLoginResponseDto.setId(user.getId());
        userLoginResponseDto.setToken(s);//这里将token返回给客户端，并由客户端主动传给后端
        userLoginResponseDto.setAvatar(user.getAvatar());
        return Result.ok(userLoginResponseDto);
    }
}
